package com.ficus.road.maintain.handler.smartdecision.handlers.highway;

import com.ficus.road.maintain.core.model.smartnew.*;
import com.ficus.road.maintain.dao.smartnew.SmartDecisionResponseDao;
import com.ficus.road.maintain.handler.smartdecision.enums.SmartDecisionStrategyEnum;
import com.ficus.road.maintain.handler.smartdecision.interfaces.SmartDecisionGroupGenerator;
import com.ficus.road.maintain.service.smartnew.SmartValuationService;
import com.ficus.road.maintain.util.FormatUtil;
import com.google.common.base.Objects;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiawen yang
 * @date 2022/7/21 下午12:00
 */
@Component
@Order(3)
@RequiredArgsConstructor
public class SmartDecisionHighwayValuationHandler extends AbstractSmartDecisionHighwayHandler implements SmartDecisionGroupGenerator {

    private static final SmartDecisionStrategyEnum STRATEGY = SmartDecisionStrategyEnum.HIGHWAY_VALUATION;
    private final SmartDecisionResponseDao smartDecisionResponseDao;
    private final SmartValuationService smartValuationService;

    @Override
    public SmartDecisionResponse doHandle(SmartDecisionRequest request, SmartDecisionResponse response) {
        SmartDecisionHighwayRequest highwayRequest = (SmartDecisionHighwayRequest) request;
        preProcess(response);
        response = strategySmartDecisionService.smartDecisionCalculate(STRATEGY, highwayRequest.getParams(), response);
        postProcess(response);
        return response;
    }

    /**
     * 计算合并PSSI（平均值）
     */
    private void preProcess(SmartDecisionResponse response) {
        List<SmartTable> tablesBeforeMerge = response.getSmartSortingResponse().getTablesBeforeMerge();
        List<SmartTable> tablesAfterMerge = response.getSmartSortingResponse().getTablesAfterMerge();
        Map<String, List<SmartTable>> mergedGroup = tablesBeforeMerge.stream().filter(item -> ObjectUtils.isNotEmpty(item.getMergedId())).collect(Collectors.groupingBy(SmartTable::getMergedId));
        mergedGroup.forEach((mergedId, list) -> {
            double pssiMerged = list.stream().filter(item -> !Objects.equal(item.getPSSI(), 0d)).mapToDouble(SmartDecisionExcelVO::getPSSI).average().orElse(100);
            tablesAfterMerge.stream().filter(item -> Objects.equal(item.getId(), mergedId)).findAny().ifPresent(mergedTable -> mergedTable.setPSSIMerge(FormatUtil.keepDecimalsOfK(pssiMerged, 2)));
        });
    }

    /**
     * 加绿化带工程
     * 保存统计数据
     */
    private void postProcess(SmartDecisionResponse response) {
        smartDecisionResponseDao.saveOrUpdate(response);
        smartValuationService.addGreenProject();
    }
}
